<template>
  <div class="audio-player fill">
    <audio
      ref="audio"
      @timeupdate="handlePlaying"
      @canplay="canplay"
      @pause="playing=false"
      @play="playing=true"
      @waiting="handleWaiting"
      @ended="handleEnd"
      :src="src"></audio>

    <div class="controls">
      <div class="play-bar"  ref="playBar" @click="handleChangeCurrent">
        <div class="total-width fill"/>
        <div class="current-width h-fill" :style="{width: currentWidth}"/>
        <div
          @mousedown="handleMoveStart"
          ref="playPoint"
          class="current-point"
          :style="{left: currentWidth}"/>
      </div>
      <div class="info-bar flex-row items-center justify-center">
        <div class="songInfo flex-row items-center">
          <template v-if="currentSong">
            <img style="height: 100%" :src="`https://y.gtimg.cn/music/photo_new/T002R300x300M000${currentSong.albummid}.jpg`" alt="">
            <div class="flex-col mnl h-fill justify-around">
              <div class="flex-row">
                <div class="name">{{currentSong.songname}}</div>
                <div class="singer text-info">
                  <span class="name msl" v-for="(item,index) in currentSong.singer" :key="index">{{item.name}}</span>
                </div>
              </div>
              <Like :like="isLike" @click.native="handleToggleLike"/>
            </div>
          </template>
        </div>
        <!--控件区-->
        <div class="btn-bar flex-row items-center">
          <div class="btn" @click="handlePrevSong">
            <WIcon  icon="icon-backward" size="22" color="white"/>
          </div>
          <div  class="play flex-center btn" @click="togglePlay">
            <WIcon v-if="playing" icon="icon-pause" size="22" color="blue"/>
            <WIcon v-else icon="icon-play" size="22" color="blue"/>
          </div>
          <div class="btn" @click="handleEnd">
            <WIcon icon="icon-forward" size="22" color="white"/>
          </div>
        </div>
        <!--时间区-->
        <div class="timeInfo flex-row items-center">
          <div class="timearea flex-row">
            <div class="time">{{current|timeFilter}}</div>/
            <div class="time">{{total|timeFilter}}</div>
          </div>
          <div class="btn" @click="handleTogglePlayMode">
            <WIcon v-if="mode===0" icon="icon-3" color="white"/>
            <WIcon v-if="mode===1" icon="icon-danqu" color="white"/>
            <WIcon v-if="mode===2" icon="icon-suiji" color="white"/>
          </div>
          <div class="playList" @click.self.stop="handleTogglePlaylist">
            播放列表<span v-if="playList.length">{{playList.length}}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import WIcon from "@/components/icon/WIcon"
import {qqMusicApi} from "@/api/table/qqmusic"
import {pass} from "@/utils/foo"
import Like from "@/layouts/window/qqMusic/components/Like"
export default {
  name: "NetworkAudioPlayer",
  components: {Like, WIcon},
  data: () => ({
    player: null,
    init: false,  // 是否被初始化过
    current: 0,  // 当前时间
    onMove: false,  // 是否在移动中
    mode: 0,  // 0/1/2 列表循环  1单一循环  2随机播放
    playList: [],
    index: 0,
    indexStack: [],
    src: "",
    playing: false,
  }),
  inject: ["setCurrentSong", "setAsidePlayList", "setIndex", "setPlayListVisible"],
  computed: {
    total() {
      return this.playing ? this.player.duration : 0
    },
    currentWidth() {
      return (this.current / this.total * 100).toFixed(2) + "%"
    },
    currentSong() {
      let song = this.playList[this.index]
      return song || null
    },
    isLike() {
      let list = this.$store.state.likeList
      if(list.find(item=>item.mid===this.currentSong.mid)){
        return true
      }else{
        return false
      }
    }
  },
  filters:{
    timeFilter(time){
      let second, minute
      minute = parseInt(time / 60)
      second = time - minute * 60
      minute = minute.toFixed(0).padStart(2, "0")
      second = second.toFixed(0).padStart(2, "0")
      return `${minute}:${second}`
    }
  },
  mounted() {
    this.player = this.$refs.audio
    window.a = this.player
  },
  methods: {
    handleWaiting() {
      this.loading = this.$loading({
        background: "#000",
        opacity: 0.9,
        target: this.$parent
      })
    },
    canplay() {
      if(this.loading){
        this.loading.close()
      }
      this.init = true
      this.player.play().catch(err=>{
        console.log(err)
      })
    },
    handlePlaying(e) {
      if (this.init && !this.onMove) {
        this.current = e.target.currentTime
      }
    },
    handlePrevSong() {
      if(this.mode===0 || this.mode===1){
        this.index = this.index === 0 ? this.playList.length - 1: this.index - 1
      }else if(this.mode===2){
        this.handleEnd()
      }
      this.startPlay()
    },
    handleEnd() {
      let maxIndex = this.playList.length
      if(this.mode===0){
        this.index = this.index + 1 > maxIndex ? 0 : this.index + 1
      }else if(this.mode===1){
        pass()
      }else if(this.mode===2){
        this.inde = Math.floor(Math.random() * (maxIndex + 1))
      }
      this.startPlay()
    },
    handleTogglePlayMode() {
      this.mode = this.mode + 1 > 2 ? 0 : this.mode + 1
      let msgMap = {
        0: "列表循环",
        1: "单一循环",
        2: "随机播放"
      }
      this.$msg.success(msgMap[this.mode])
    },
    // 点选
    handleChangeCurrent(e) {
      if(e.target===this.$refs.playPoint || this.onMove){
        return
      }
      let barWidth = this.$refs.playBar.clientWidth
      let offsetX = e.offsetX
      let totalX = barWidth
      let percent = offsetX / totalX
      this.player.currentTime = this.total * percent
    },
    // 移动
    handleMoveStart(e) {
      let barWidth = this.$refs.playBar.clientWidth
      let target =  this.$refs.playPoint
      this.onMove = true
      let startX = e.x
      let offsetX = target.offsetLeft
      let moveHandler = e => {
        let delta = e.x - startX
        let endX =  offsetX + delta
        endX = Math.max(endX, 0)
        endX = Math.min(endX, barWidth)
        let percent = endX / barWidth
        this.current = this.total * percent
        target.style.left = percent * 100 + "%"
      }
      let mouseUpHandler = () => {
        let percent = target.offsetLeft / barWidth
        this.player.currentTime = this.total * percent
        this.onMove = false
        window.removeEventListener("mousemove", moveHandler)
        window.removeEventListener("mouseup", mouseUpHandler)
      }
      window.addEventListener("mousemove", moveHandler)
      window.addEventListener("mouseup", mouseUpHandler)
    },
    // 播放暂停点击
    togglePlay() {
      if(!this.player){
        this.$msg.warning("等待播放器初始化")
      }
      if(this.playing){
        this.player.pause()
      }else{
        this.player.play()
      }
    },
    setNetworkList(playlist, index) {
      this.playList = playlist
      this.setAsidePlayList(playlist)
      this.index = index
      this.startPlay()
    },
    setPlayListIndex(index) {
      this.index = index
      this.startPlay()
    },
    // 启动!
    startPlay() {
      let target = this.playList[this.index]
      if(!target){
        return
      }
      this.setIndex(this.index)
      this.setCurrentSong(target)
      qqMusicApi.getSongSrc(target.songmid).then(ret=>{
        if(ret.data && ret.data.startsWith("http")){
          this.processBug(target)
          this.$store.commit("addMusicHis", target)
          this.src = ret.data
          this.player.play().catch(err=>err)
        }else{
          this.$msg.warning("获取播放链接失败")
        }
      })
    },
    processBug(target) {
      if(!target.albumname){
        target.albumname = target.album.name
        target.albummid = target.album.mid
      }
    },
    handleTogglePlaylist(e) {
      console.log("eee", e)
      this.setPlayListVisible(true)
    },
    handleToggleLike() {
      this.$store.commit("toggleLike", this.currentSong)
    }
  }
}
</script>

<style scoped lang="scss">
@import "~@/assets/css/var";
.audio-player {
  position: relative;
  user-select: none;
  color: white;
}

.controls {
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  background-color: #22345d;
  height: 80px;

  .play-bar {
    margin: 10px auto;
    width: 90%;
    height: 5px;
    position: relative;
    cursor: pointer;
    //border: 1px solid red;
    .total-width {
      position: absolute;
      background-color: #29e7fe;
      cursor: pointer;
    }

    .current-width{
      position: absolute;
      background-color: #909399;
      width: 0;
    }

    .current-point{
      position: absolute;
      width: 15px;
      height: 15px;
      top: 50%;
      border-radius: 50%;
      background-color: blueviolet;
      border: 1px solid white;
      transform: translate(-50%, -50%);
      cursor: pointer;
    }
  }
  .info-bar{
    position: relative;
    height: 42px;
    .songInfo{
      height: 100%;
      width: 300px;
      overflow: hidden;
      .singer{
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
      img{
        height: 100%;
      }
    }
    .btn-bar{
      .btn{
        cursor: pointer;
        margin: 0 $mn;
      }
      .play{
        background-color: #29e7fe;
        padding: 10px;
        border-radius: 50%;
      }
    }
    .songInfo{
      position: absolute;
      padding-left: $pl;
      left: 0;
    }
    .timeInfo{
      position: absolute;
      right: 0;
      padding-right: $pl;
      &>*{
        margin: $mn;
      }
      .timearea{
        color: $text-info;
      }
    }
  }
  .playList{
    color: $text-info;
    overflow: hidden;
  }
}
</style>
